﻿using System;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private string iniPath = "./Setting.ini";
        decimal Rmax, Rmin, Vmin, Vmax;
        int index = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {


            OperateIniFile F_operateIni = new OperateIniFile();

            this.toolStripStatusLabel1.Text = F_operateIni.ReadIniData("COM", "PortName", iniPath);
            this.toolStripStatusLabel2.Text = F_operateIni.ReadIniData("COM", "BaudRate", iniPath);
            this.toolStripStatusLabel3.Text = F_operateIni.ReadIniData("COM", "Parity", iniPath);
            this.toolStripStatusLabel4.Text = F_operateIni.ReadIniData("COM", "DataBits", iniPath);
            this.toolStripStatusLabel5.Text = F_operateIni.ReadIniData("COM", "StopBits", iniPath);
            this.toolStripStatusLabel6.Text = DateTime.Now.ToString();

            this.toolStripStatusLabel6.Alignment = ToolStripItemAlignment.Right;

            Rmax = decimal.Parse(F_operateIni.ReadIniData("MEASURE", "Rmax", iniPath));
            Rmin = decimal.Parse(F_operateIni.ReadIniData("MEASURE", "Rmin", iniPath));
            Vmax = decimal.Parse(F_operateIni.ReadIniData("MEASURE", "Vmax", iniPath));
            Vmin = decimal.Parse(F_operateIni.ReadIniData("MEASURE", "Vmin", iniPath));

            //设置串口号
            serialPort1.PortName = this.toolStripStatusLabel1.Text;

            //设置串口速率
            serialPort1.BaudRate = Convert.ToInt32(this.toolStripStatusLabel2.Text);

            //设置效验位
            string s = this.toolStripStatusLabel3.Text;
            if (s.CompareTo("无") == 0)
            {
                serialPort1.Parity = System.IO.Ports.Parity.None;
            }
            if (s.CompareTo("奇效验") == 0)
            {
                serialPort1.Parity = System.IO.Ports.Parity.Odd;
            }
            if (s.CompareTo("偶效验") == 0)
            {
                serialPort1.Parity = System.IO.Ports.Parity.Even;
            }

            serialPort1.DataBits = Convert.ToInt32(this.toolStripStatusLabel4.Text);

            //设置停止位
            string f = this.toolStripStatusLabel5.Text;
            if (f.CompareTo("0") == 0)
            {
                serialPort1.StopBits = System.IO.Ports.StopBits.None;
            }
            if (f.CompareTo("1") == 0)
            {
                serialPort1.StopBits = System.IO.Ports.StopBits.One;
            }
            if (f.CompareTo("2") == 0)
            {
                serialPort1.StopBits = System.IO.Ports.StopBits.Two;
            }
            comboBox1.SelectedIndex = 1;
            string Cellmodel = F_operateIni.ReadIniData("MEASURE", "Cellmodel", iniPath);
            string[] grid_mode = Cellmodel.Split(',');
            foreach (string i in grid_mode)
            {
                comboBox2.Items.Add(i);

            }
        }

        private void button5_Click(object sender, EventArgs e)
        {

            int k = dataGridView1.SelectedRows.Count;
            if (k != dataGridView1.Rows.Count + 1)
            {
                for (int i = k; i >= 1; i--)
                {
                    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i - 1].Index);
                }
            }
            label12.Text = dataGridView1.Rows.Count.ToString();
        }

        private void 串口参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Form2().ShowDialog();
        }

        private void button4_Click(object sender, EventArgs e)

        {
            if (serialPort1.IsOpen)
            {

                label8.Text = "开始测量";
                button4.Enabled = false;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {

            button4.Enabled = true;
            label8.Text = "结束测量";
        }

        #region 导出表格数据

        private void button6_Click(object sender, EventArgs e)
        {


            if (dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.FileName = null;
            saveFileDialog.Title = "保存";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = saveFileDialog.OpenFile();

                StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
                string strLine = "";
                try
                {
                    //表头
                    for (int i = 0; i < dataGridView1.ColumnCount; i++)
                    {
                        if (i > 0)
                            strLine += ",";
                        strLine += dataGridView1.Columns[i].HeaderText;
                    }
                    strLine.Remove(strLine.Length - 1);
                    sw.WriteLine(strLine);
                    strLine = "";
                    //表的内容

                    toolStripProgressBar1.Visible = true;//设置进度条可见
                    toolStripProgressBar1.Value = 0;//设置进度条当前值为0
                    toolStripProgressBar1.Minimum = 0;//设置进度条最小值为0
                    toolStripProgressBar1.Maximum = (int)dataGridView1.Rows.Count;

                    for (int j = 0; j < dataGridView1.Rows.Count; j++)
                    {
                        strLine = "";
                        int colCount = dataGridView1.Columns.Count;
                        toolStripProgressBar1.PerformStep();
                        for (int k = 0; k < colCount; k++)
                        {
                            if (k > 0 && k < colCount)
                                strLine += ",";
                            if (dataGridView1.Rows[j].Cells[k].Value == null)
                                strLine += "";
                            else
                            {
                                string cell = dataGridView1.Rows[j].Cells[k].Value.ToString().Trim();
                                //防止里面含有特殊符号
                                cell = cell.Replace("\"", "\"\"");
                                //cell = "\"" + cell + "\""; //每个元素值用引号包括
                                strLine += cell;
                            }
                        }
                        sw.WriteLine(strLine);
                    }
                    sw.Close();
                    stream.Close();
                    MessageBox.Show("数据被导出到：" + saveFileDialog.FileName.ToString(), "导出完毕", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    toolStripProgressBar1.Visible = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            return;
        }

        #endregion 导出表格数据


        private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            //e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }
        private void button2_Click(object sender, EventArgs e)
        {

            textBox2.Text = GetWeight();
            DataGridViewRow dr = new DataGridViewRow();
            dr.CreateCells(dataGridView1);
            dr.Cells[0].Value = ++index;
            dr.Cells[1].Value = DateTime.Now.ToString("d");
            dr.Cells[2].Value = DateTime.Now.ToString("T");
           dr.Cells[3].Value = textBox3.Text;
            dr.Cells[5].Value = textBox2.Text;
          //  dr.Cells[8].Value = textBox1.Text;
          //  dr.Cells[10].Value = comboBox1.Text;
            this.dataGridView1.Rows.Insert(0, dr);
            this.dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
            label12.Text = dataGridView1.Rows.Count.ToString();
            textBox3.Clear();
            textBox3.Focus();
            //textBox1.Text = "00.0000";
            //textBox2.Text = "00.0000";

        }

        public static string   GetWeight()
        {
            string Weight="2.00";
            string logfile ="LOG" + DateTime.Now.ToString("yyyy-MM-dd") + ".TXT";
            string directoryPath = @"log";
            string filePath = Path.Combine(directoryPath, logfile);
            Directory.CreateDirectory(directoryPath);
            string savelog = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " --> " + Weight + "\r\n";
            File.AppendAllText(filePath, savelog);


            return Weight;
        }


    
    private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.button2_Click(sender, e);

            }
        }
        //private void timer1_Tick(object sender, EventArgs e)
        //{
        //    serialPort1.Write(":FETCh?\r\n");
        //}
        private void button1_Click(object sender, EventArgs e)
        {

            if (button1.Text == "断开设备")

            {
                serialPort1.Close();
                button1.Text = "连接设备";
                label7.Text = "连接失败";
               
                button4.Enabled = true;
                label8.Text = "测量结束";
            }
            else
            {
                try
                {

                    serialPort1.Open();
                    serialPort1.Write(":TRIGger:SOURce IMM\r\n");
                    serialPort1.Write(":INITiate:CONTinuous ON\r\n");
                    label7.Text = "连接成功";
                    button1.Text = "断开设备";
                }
                catch (Exception)
                {
                    label7.Text = "连接失败";
                }
            }

        }
    }
}